<template>
  <div class="slave-main">
    <div class="slave-main dialog-main">
      <div class="filter-container">
        <el-button
          class="filter-item"
          :type="inManager"
          icon="el-icon-edit"
          size="medium"
          @click="listCaseInManager()"
        >管理用例</el-button>
        <el-button
          class="filter-item"
          :type="notInManager"
          icon="el-icon-plus"
          size="medium"
          @click="listCaseNotInManager()"
        >新增用例</el-button>
        <el-button v-if="batchBar=='del'" class="filter-item" type="danger" icon="el-icon-delete" size="medium" @click="batchDelHandle(0)">
          批量删除
        </el-button>
        <el-button v-if="batchBar=='add'" class="filter-item" type="danger" icon="el-icon-plus" size="medium" @click="batchDelHandle(1)">
          批量新增
        </el-button>
        <el-button :disabled="batchBar=='add'" class="filter-item" type="success" icon="" size="medium" @click="openSortSetCase">
          排序用例
        </el-button>
        <el-button class="filter-item export" type="primary" icon="el-icon-download" size="medium" @click="exportExcelHandle">
          导出
        </el-button>

      </div>
      <el-table
        border
        highlight-current-row
        :data="pageData"
        style="width: 100%"
        @selection-change="selectRowHandle"
        @sort-change="tableSortChange"
        ref="caseTable"
      >
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column prop="map_id" label="ID" align="center" width="80" sortable />
        <el-table-column prop="classed_path" align="center" label="用例分类" :show-overflow-tooltip="true" min-width="200" sortable />
        <el-table-column prop="case_num" align="center" label="用例编号" :show-overflow-tooltip="true" min-width="120" sortable />
        <el-table-column prop="case_title" align="center" :show-overflow-tooltip="true" min-width="200" label="用例名称" sortable />
        <el-table-column prop="step_count" align="center" label="测试步骤" sortable width="110">
          <template slot-scope="scope">
            <router-link :to="'/caseCategory/step/' + scope.row.id + '/' + scope.row.case_title">
              <el-tag class="step-count" :type="scope.row.step_count === 0 ? 'info': ''">{{ scope.row.step_count }}</el-tag>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="case_type" align="center" label="用例类型" :show-overflow-tooltip="true" sortable width="110" />
        <el-table-column prop="seq_num" align="center" label="执行顺序" width="110" sortable />
        <el-table-column prop="create_time" align="center" label="创建时间" min-width="160" sortable />
        <el-table-column prop="creator_name" align="center" label="创建人" min-width="130" sortable />
        <el-table-column prop="mark" align="center" min-width="180" :show-overflow-tooltip="true" label="备注" sortable />
        <el-table-column label="操作" fixed="right" header-align="center" align="center" min-width="80">
          <template slot-scope="scope">
            <div v-if="caseManager.mode === 1">
              <el-button type="text" size="small" @click="editHandle(scope.row,0)">新增</el-button>
            </div>
            <div v-if="caseManager.mode === 0">
              <!-- <el-button type="text" size="small" @click="editHandle(scope.row,1)">编辑</el-button> -->
              <el-button type="text" size="small" @click="editHandle(scope.row,1)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="pageIndex"
          :page-sizes="[10, 15, 30, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <sort-object ref="sortTable" @get-sort-ids="getSortIds"></sort-object>
  </div>
</template>

<script>
import { listCase, listCaseNotInSet, addCase2Set, delCase2Set, sortSetCase } from '@/api/caseSet'
import { exportExcel1 } from '@/utils/exportExcelUtils'
import SortObject from '@/components/sortObject'

export default {
  name: 'CaseSetManager',
  components: {
    SortObject
  },
  props: {
    setId: {
      type: String,
      default: ''
    },
    setName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tableData: [],
      filterTableData: [], // 前端搜索之后的数据
      selectIds: [],
      selectMapIds: [],
      pageSize: 10, // 每页大小默认值
      pageIndex: 1, // 默认第一页
      caseManager: {
        setId: '',
        setName: '',
        mode: 0 // 按钮控制
      },
      showDialog: false,
      caseStepItem: {
        caseId: '',
        title: '',
        visible: false
      },
      inManager: '',
      notInManager: '',
      batchBar: 'del'
    }
  },
  computed: {
    // 总数
    total() {
      return this.tableData.length
    },
    // 当前分页数据
    pageData() {
      return this.tableData.slice((this.pageIndex - 1) * this.pageSize, this.pageIndex * this.pageSize)
    }

  },
  watch: {
    tableData() {
      this.pageIndex = 1
    }
  },
  mounted() {
    this.caseManager.setId = this.setId
    this.caseManager.setName = this.setName
    const title = '测试用例管理'
    const route = Object.assign({}, this.$route, { title: `${title} - ${this.caseManager.setName}` })
    this.$store.dispatch('tagsView/updateVisitedView', route)
    document.title = `${title} - ${this.caseManager.setName}`
    this.listCaseInManager()
  },
  methods: {
    // 打开用例排序界面
    openSortSetCase() {
      const sortTableData = []
      this.tableData.forEach(item => {
        sortTableData.push({
          id: item.map_id,
          title: item.case_title,
          seq: item.seq_num
        })
      })
      this.$refs.sortTable.init(sortTableData, '用例排序')
    },
    // 子组件回传排序完成的ids
    getSortIds(ids) {
      sortSetCase(ids).then(() => {
        this.$refs.sortTable.sortVisible = false
        this.listCaseInManager()
        this.$message.success('排序成功')
      })
    },
    // 表格头排序
    tableSortChange({ column, prop, order }) {
      if (order === null) {
        this.handleFilter()
        return false
      }
      this.tableData.sort(function(a, b) {
        return order === 'ascending' ? a[prop] - b[prop] : b[prop] - a[prop]
      })
    },
    selectRowHandle(selection) {
      this.selectIds = []
      this.selectMapIds = []
      const self = this
      selection.forEach(function(row) {
        self.selectIds.push(row.id)
        self.selectMapIds.push(row.map_id)
      })
    },
    handleFilter() {
      const data = []
      Object.assign(data, this.tableData)
      this.tableData = data
    },
    // 前端分页： 当前页码改变
    handleCurrentChange(val) {
      this.pageIndex = val
    },
    // 前端分页：分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
    },
    // 获取用例列表
    async listCaseInManager() {
      this.caseManager.mode = 0
      const params = {
        set_id: this.caseManager.setId
      }
      this.inManager = 'primary'
      this.notInManager = ''
      this.batchBar = 'del'
      listCase(params).then(response => {
        this.tableData = response.data
        this.handleFilter()
      })
    },
    listCaseNotInManager() {
      this.caseManager.mode = 1
      const params = {
        set_id: this.caseManager.setId
      }
      this.inManager = ''
      this.notInManager = 'primary'
      this.batchBar = 'add'
      listCaseNotInSet(params).then(response => {
        this.tableData = response.data
        this.handleFilter()
      })
    },
    editHandle(row, state) {
      if (row.id === '' || row.id === undefined) {
        this.$message.error('未获取到测试用例id')
        return
      }

      if (state === 0) {
        const data = [row.id]
        this.$confirm('确定添加【' + row.case_title + '】至测试集中吗 ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          addCase2Set(data, this.caseManager.setId).then(response => {
            this.listCaseNotInManager()
            this.$message.success('添加成功')
          })
        }).catch(() => {
        })
      } else { // 删除
        const data = [row.map_id]
        this.$confirm('确定将【' + row.case_title + '】从测试集中删除吗 ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delCase2Set(data).then(response => {
            this.listCaseInManager()
            this.$message.success('删除成功')
          })
        }).catch(() => {
        })
      }
    },
    exportExcelHandle() {
      const tHeader = ['ID', '用例分类', '用例编号', '用例名称', '测试步骤', '用例类型', '执行顺序', '创建时间', '创建人', 'mark']// 上面设置Excel的表格第一行的标题
      const filterVal = ['id', 'classed_path', 'case_num', 'case_title', 'step_count', 'case_type', 'status', 'create_time', 'creator_name', 'mark'] // 上面的index、nickName、name是tableData里对象的属性
      const list = this.tableData // 把data里的tableData存到list
      const excelName = '测试用例'
      exportExcel1(tHeader, filterVal, list, excelName)
    },
    batchDelHandle(type) {
      if (this.selectMapIds.length === 0) {
        this.$message.warning('请先选择至少一行数据!')
        return
      }
      if (type === 0) {
        this.batchDel()
      } else {
        this.batchAdd()
      }
    },
    batchAdd() {
      const self = this
      this.$confirm('是否批量新增选择的 ' + this.selectIds.length + ' 条数据？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = []
        self.selectIds.forEach(function(val) {
          data.push(val)
        })
        addCase2Set(data, this.caseManager.setId).then(response => {
          self.listCaseNotInManager()
          self.$notify({
            title: '通知',
            message: '添加成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch()
    },
    batchDel() {
      let failCount = 0
      const self = this
      this.$confirm('是否批量删除选择的' + this.selectIds.length + ' 条数据？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectMapIds.forEach(function(val) {
          delCase2Set([val]).then(response => {
          }).catch(() => {
            failCount++
          })
        })
        const intervalId = setInterval(function() {
          clearInterval(intervalId)
          if (self.caseManager.mode === 1) {
            self.listCaseNotInManager()
          } else {
            self.listCaseInManager()
          }
          if (failCount === 0) {
            self.$notify({
              title: '通知',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            self.$notify({
              title: '通知',
              message: '共' + failCount + '条数据删除失败',
              type: 'error',
              duration: 2000
            })
          }
        }, 300)
      }).catch()
    }
  }

}
</script>

<style scoped>
  /deep/ .sortable-ghost {
    opacity: 0.8;
    color: #fff !important;
    background: #42b983 !important;
  }

  .dialog-main{
    padding: 20px 20px;
  }
  .export{
    float: right;
  }
</style>
